<template>
  <xy-page>
    <div class="viewMenu">
      <div class="menu">
        <div class="fl menu-text cursor" @click="dialogVisible = true">添加菜单</div>
        <div class="fl mgl20 menu-text cursor" @click="menuManage">菜单管理</div>
        <!-- 添加菜单 -->
        <el-dialog title="添加菜单" :visible.sync="dialogVisible" width="30%" :modal="false" :close-on-click-modal="false" style="z-index:999">
          <el-form :model="form" class="txtC">
            <div>
              <span class="wd90">菜单名称:</span>
              <el-input v-model="form.menutitle" class="w300"></el-input>
            </div>
            <div class="mgt20">
              <span>菜单类型:</span>
              <el-select v-model="form.menuValue" class="w300">
                <el-option
                  v-for="item in form.menuType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  v-show="haveType.indexOf(item.value) == -1"
                ></el-option>
              </el-select>
            </div>
            <div class="mgt20" v-show="form.menuValue == 'iframe'">
              <span>外链地址:</span>
              <el-input v-model="form.iframeUrl" class="w300"></el-input>
            </div>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addMenu" :loading="loading">确认添加</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
          </span>
        </el-dialog>

        <!-- 菜单管理 -->
        <el-dialog title="菜单管理" :visible.sync="istrationVisible" width="720px" :modal="false" :close-on-click-modal="false">
          <el-form :model="form" class="txtC">
            <div>
              提示：如需关闭提问功能，请前往功能开关处关闭
              <el-button type="text" @click="gotoSwitch">前往设置>></el-button>
            </div>
            <el-table :data="copyList" stripe class="mgt20">
              <el-table-column label="菜单名称" width="150" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.title" class="w100" maxlength="8" show-word-limit></el-input>
                  <span>{{scope.row.title.length}}/8</span>
                </template>
              </el-table-column>
              <el-table-column label="菜单类型" width="120" align="center">
                <template slot-scope="scope">
                  {{scope.row.menuType | menuType}}
                </template>
              </el-table-column>
              <el-table-column label="菜单顺序" min-width="180" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="upWard(scope.$index)" :disabled="scope.$index == 0">上移</el-button>
                  <el-button type="text" @click="downWard(scope.$index)" :disabled="scope.$index == copyList.length - 1">下移</el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="del(scope.$index)" v-show="scope.row.menuType != 'quiz'">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="updateMenu" :loading="loading">确认修改</el-button>
            <el-button @click="istrationVisible = false">取 消</el-button>
          </span>
        </el-dialog>
      </div>
      
      <div class="context">
        <el-tabs v-model="activeOrder" style="width:650px;display:inline-block;float:left" ref="menutab" @tab-click="handleClick">
            <el-tab-pane
              v-for="(item,index) in menuList"
              :label="item.title"
              :name="item.name"
              :key="index">
            </el-tab-pane>
            <div v-show="showType=='desc' || showType=='text'">
              
              <div style="z-index:1;position: relative;">
                <div id="editorElem" style="text-align:left" ref="editorElem"></div>
              </div>
              <el-button type="primary" class="mgt40" @click.stop="saveQuill">保存</el-button>
            </div>
            <div class="context-text" v-show="showType=='quiz' || showType=='chat'">
              当前为{{menuList[indexMenu] && menuList[indexMenu].title}}模块<br/>
              {{menuList[indexMenu] && menuList[indexMenu].title}}模块为系统默认样式
            </div>
            <div v-show="showType=='iframe'">
              <el-form>
                <el-form-item label="推广外链">
                  <el-input type="text" style="width: 300px;" v-model="iframeUrl"></el-input>
                  <div>
                    <el-button type="primary" class="mgt40" @click.stop="saveQuill">保存</el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
        </el-tabs>
      </div>

      <!-- 预览 -->
      <div class="preview">
        <div class="txtC ">移动端预览，PC端页面效果请<el-button type="text" @click="openUrl">点击这里</el-button></div>
        <div class="phone">
          <img class="phone-header" src="/static/images/previewHeader.png">
          <div class="menuPanel">
            <el-tabs v-model="activeOrder" class="phone-tabs">
              <el-tab-pane
                disabled
                v-for="(item,index) in menuList"
                :label="item.title"
                :name="item.name"
                :key="index"
              ></el-tab-pane>
            </el-tabs>  
          </div>
          
          <div class="bg-text" >
            <div class="bg-text" v-if="showType=='quiz'">
              <img class="phone-img" src="/static/images/weichat.jpg">
            </div>
            <div class="bg-text" v-else-if="showType=='chat'">
              <img class="phone-img" src="/static/images/tiwen.jpg">
            </div>
            <div class="bg-text" v-else-if="showType=='iframe'">
              <iframe :src="iframeUrl" frameborder="0" class="bg-text"></iframe>
            </div>
            <div class="preview-text" v-else v-html="content"></div>
          </div>
        </div>
      </div>
      <!-- 这个el-upload用于富文本图片上传 -->
      <el-upload :data="uploadParam" class="uploader" :show-file-list="false" :action="signatureData.host" accept="image/*" :on-success="uploadSuccess" :on-error="uploadError" :on-change="beforeUpload"></el-upload>
    </div>
  </xy-page>
</template>
<script>
import Editors from 'wangeditor';
export default {
  data() {
    return {
      appId:'',
      channelId:'',
      activeOrder: '1',
      content: '',
      editor:'',
      iframeUrl: '',
      fileList: [],
      signatureData: {
        host: ''
      }, // oss签名数据
      uploadParam: {}, // 图片上传参数
      dialogVisible: false, // 添加菜单弹窗
      istrationVisible: false, // 菜单管理弹窗
      form: {
        menutitle: '',
        menuValue:'',
        iframeUrl: '',
        menuType: [
          { value: 'desc', label: '直播介绍' },
          { value: 'chat', label: '互动聊天' },
          { value: 'quiz', label: '咨询提问' },
          { value: 'text', label: '图文菜单' },
          { value: 'iframe', label: '推广外链' }
        ],
      },
      showType:'',
      menuList: [],
      loading: false,
      indexMenu: 0,
      copyList: [],
      haveType: '', // 已有的菜单类型
      watchUrl: '',
      temp:'',
      key:''
    }
  },
  methods: {
    openUrl(){
      if(this.watchUrl){
        this.$utils.linkTo(this.watchUrl)
      }else{
        this.getWatchUrl(()=> {
          this.$utils.linkTo(this.watchUrl)
        })
      }
    },
    getWatchUrl(cb){
      this.$postStream('/admin/instance/ccb/polyv/channel/sample.do', {
        data: {
          appId: this.appId,
          channelId: this.channelId,
        },
        success: res => {
          if (res.success) {
            this.watchUrl = res.object.url
            cb && cb()
          }
        }
      })
    },
    // 去功能开关
    gotoSwitch() {
      this.$toPage('/broadcast/liveSwitch')
    },
    //添加菜单列表
    addMenu() {
      this.loading = true
      let content = ''
      if(!this.form.menutitle.trim()){
        this.$message.error('菜单名称不能为空')
        this.loading = false
        return
      }
      if(this.form.menuValue == ''){
        this.$message.error('菜单类型不能为空')
        this.loading = false
        return
      }
      if(this.form.menuValue == 'iframe'){
        if(!this.$utils.isHttp(this.form.iframeUrl)){
          this.$message.error('请输入正确的链接地址')
          this.loading = false
          return
        }else{
          content = this.form.iframeUrl
        }
      }
      this.$postStream('/admin/instance/ccb/polyv/pageview/menu/addMenu.do',{
        data:{
          appId: this.appId,
          channelId: this.channelId,
          type: this.form.menuValue,
          name: this.form.menutitle,
          content: content
        },
        success: res=>{
          if(res.success){
            this.$nextTick(()=>{
              this.form.menutitle = ''
              this.form.menuValue = ''
              this.form.iframeUrl = ''
              this.activeOrder = res.object.ordered + ''
              this.getMenuList()
              this.dialogVisible = false
            })
          }else{
            res.code == 50001?this.$message.error(res.message):this.$message.error('添加菜单失败!')
          }
        },
        complete: ()=>{
          this.loading = false
        }
      })
    },
    // 获取菜单列表
    getMenuList(){
      this.$postStream('/admin/instance/ccb/polyv/pageview/menu/listMenu.do',{
        data:{
          appId: this.appId,
          channelId: this.channelId,
        },
        success: res => {
          if(res.success){
            this.haveType = ''
            this.menuList = res.object.map(element=>{
              if(element.menuType != 'text' && element.menuType != 'iframe'){
                this.haveType += element.menuType + ' '
              }
              return{
                checked:false,
                title: element.name,
                name: element.ordered+'',
                menuType:element.menuType,
                menuId: element.menuId,
                content: element.content
              }
            })
            this.$nextTick(() => {
              this.showType = this.menuList[this.activeOrder - 1].menuType
              this.content = this.menuList[this.activeOrder - 1].content
              this.iframeUrl = this.menuList[this.activeOrder - 1].content
              this.editor && this.editor.txt.html(this.content)
            })
          }else{
            this.$message.error('获取菜单列表失败!')
          }
        }
      })
    },
    //菜单详情
    handleClick(tab) {
      this.indexMenu = tab.index
      this.showType = this.menuList[this.indexMenu].menuType
      this.content = this.menuList[this.indexMenu].content || ''
      this.iframeUrl = this.menuList[this.indexMenu].content
      this.$nextTick(()=>{
        this.editor.txt.html(this.content)
      })
      
    },
    //菜单修改
    updateMenu(){
      let dataList = []
      this.copyList.forEach(item => {
        let temp = {}
        temp[item.menuId] = item.title
        dataList.push(temp)
      })
      this.$postStream('/admin/instance/ccb/polyv/pageview/menu/batchDeleteMenu.do',{
        data:{
          appId: this.appId,
          channelId: this.channelId,
          menuList: JSON.stringify(dataList)
        },
        success:res=>{
          if(res.success){
            this.$message.success('修改成功!')
            this.istrationVisible = false
            this.activeOrder = '1'
            this.getMenuList()
          }else{
            res.code == 50001?this.$message.error(res.message):this.$message.error('修改失败!')
          }
        }
      })
    },
    // 菜单管理
    menuManage(){
      this.copyList = JSON.parse(JSON.stringify(this.menuList))
      this.istrationVisible = true
      this.$forceUpdate()
    },
    //上移
    upWard(index){
      let temp = this.copyList[index-1]
      this.copyList[index-1] = this.copyList[index]
      this.copyList[index] = temp
      // 解决列表渲染慢的问题
      let tempList = this.copyList
      this.copyList = []
      this.copyList = tempList
    },
    //下移
    downWard(index){
      let temp = this.copyList[index+1]
      this.copyList[index+1] = this.copyList[index]
      this.copyList[index] = temp
      
      let tempList = this.copyList
      this.copyList = []
      this.copyList = tempList
    },
    del(index){
      this.copyList.splice(index, 1)
    },
    //菜单内容保存
    saveQuill(){
      let content = ''
      if(this.menuList[this.indexMenu].menuType == 'iframe'){
        content = this.iframeUrl
      }else{
        if(this.editor.txt.html()=='<p><br></p>'){
          this.$message.error('内容不能为空')
          return
        }
        content = this.editor.txt.html()
      }
      this.$postStream('/admin/instance/ccb/polyv/pageview/menu/updateMenuById.do',{
        data:{
          appId: this.appId,
          channelId: this.channelId,
          content: content,
          menuId: this.menuList[this.indexMenu].menuId
        },
        success: res => {
          if(res.success){
            this.$message.success('保存成功!')
          }else{
            res.code == 50001?this.$message.error(res.message):this.$message.error('保存失败!')
          }
        }
      })
    },
    beforeUpload(file){
      if(file.size/1024/1024 > 4){
        this.$message.warning('图片大小不能大于4M')
        return false
      }
      var temp = file.name.split(".")
      let uuid = this.UUID()
      var key = this.signatureData.dir + uuid + "." + temp[temp.length - 1]
      this.uploadParam.policy = this.signatureData.policy
      this.uploadParam.OSSAccessKeyId = this.signatureData.OSSAccessKeyId
      this.uploadParam.success_action_status = '200'
      this.uploadParam.signature = this.signatureData.signature
      this.uploadParam.key = key
      this.uploadParam.name = file.name
    },
    //上传图片
    //获取oss信息
    getOssInfo(){
      this.$postStream('/admin/instance/ccb/polyv/getOssInfo.do',{
        data:{
          appId:this.appId
        },
        success: res=> {
          if(res.success){
            if(!this.$utils.isHttp(res.object.host)){
              this.signatureData.host = 'http://' + res.object.host
            }
            this.signatureData={
              policy: res.object.policy,
              OSSAccessKeyId: res.object.accessid,
              success_action_status: "200",
              signature: res.object.signature,
              dir:res.object.dir,
              host:this.signatureData.host
            }
            // this.fullEditor()
          }
        }
      })
    },
    //生成文件名
    UUID(){
      var s = []
      var hexDigits = "0123456789abcdef"
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = "4"
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
      s[8] = s[13] = s[18] = s[23] = "-"
      var uuid = s.join("")
      return uuid
    },
    uploadSuccess(){
      this.$message.success('上传成功')
      let uploadImg = this.signatureData.host + "/" + this.uploadParam.key
      this.content = this.content + '<img src="' + uploadImg + '"/>'
      this.editor.txt.html(this.content)
    },
    uploadError(){
      this.$message.error('图片插入失败')
    },
    //上传富文本
    fullEditor(){
      this.editor = new Editors('#editorElem')
      // 配置菜单
      this.editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'unorderlist',	// 无序列表
        'orderlist',	// 有序列表
        'justify', // 对齐方式
        'quote', // 引用
        'image', // 插入图片
        'table', // 表格
        'list',  // 列表
      ]
      //文本内容
      this.editor.customConfig.onchange = (html) => {
        this.content = html
      }
      //利用element上传图片
      this.editor.customConfig.qiniu = true
      // 隐藏“网络图片”tab
      this.editor.customConfig.showLinkImg = false
      this.editor.create()
      this.editor.txt.html(this.content)
      document.querySelector('.w-e-icon-image').onclick = () =>{
        document.querySelector('.uploader input').click()
      }
    }
  },
  mounted() {
    this.channelId = sessionStorage.getItem('channelId')
    this.appId = sessionStorage.getItem('appId') || ''
    this.getOssInfo()
    this.fullEditor()
    this.getMenuList()
  }
};

</script>

<style lang="scss">
@import '../../../assets/scss/mixin.scss';
.viewMenu {
  position: relative;
  width: 100%;
  .menu {
    position: absolute;
    z-index: 22;
    left: 500px;
    height: 40px;
    line-height: 40px;
    .menu-text {
      text-decoration: underline;
    }
  }
  .context{
    width: 650px;
    display: inline-block;
    .context-text{
      text-align: center;
      padding-top: 100px;
    }
  }
  .ql-container.ql-snow {
    border: 1px solid #ccc;
    height: 300px;
  }
  .editor{
    width:625px;
    border:1px solid #ccc;
  }
  // 预览
  .preview {
    position: absolute;
    left: 680px;
    display: inline-block;
  }
  .phone-header{
    width: 100%;
    height: 200px;
  }
  .phone{
    width: 225px;
    height: 400px;
    overflow: hidden;
    position: relative;
    border: 1px solid #e6e6e6;
    
    .menuPanel{
      width: 100%;
      height: 32px;
      line-height: 32px;
      .el-tabs__header{
        height: 32px;
        line-height: 32px;
      }
      .el-tabs__item{
        height: 32px;
        line-height: 32px;
        font-size: 12px !important;
        padding-left: 16px !important; 
        padding-right: 16px !important; 
      }
      .is-scrollable .el-tabs__item.is-top:nth-child(2){
        padding-left: 0px !important;
      }
      .is-scrollable .el-tabs__item.is-top:last-child{
        padding-right: 0px !important;
      }
      .el-tabs__nav-prev, .el-tabs__nav-next{
        height: 32px;
        line-height: 32px;
      }
    }
    .bg-text{
      width: 100%;
      height: 170px;
      overflow-y: auto;
      th,tr{
        border: 1px solid #ccc;
      }
      @include scroll();
      .preview-text{
        position: relative;
        font-size: 12px;
        word-wrap: break-word;
        border: none;
        width: 100%;
        background: #fff;
        padding: 10px;
        p{
          margin: 0;
        }
        img{
          max-width: 100%;
        }
        table th,td{
          border: 1px solid #ccc;
        }
      }
      .phone-img{
        width: 100%;
        height: 100%;
      }
    }
  }
}
.w-e-text table th,tr{
  text-align: left;
}

.w-e-text img{
  max-width: 600px;
}
.w-e-text ul, .w-e-text ol{
  margin: 0;
}
.w-e-text ol,.preview-text ol{
  list-style-type:none;
  counter-reset:sectioncounter;
}
.w-e-text ol li:before,.preview-text ol li:before {
  content:counter(sectioncounter) "."; 
  counter-increment:sectioncounter;
}
.w-e-text ul,.preview-text ul{
  padding-left: 15px;
}

</style>
